var express = require("express");
var router = express.Router();
var check = require("../middleware/check");
var path = require("path");
var db = require("../db");
var path = require("path");

const createError = require("http-errors");

const { ObjectId } = require("bson");

// 发表文章
router.get("/WriteArticles", check.checkLogin, function (req, res, next) {
  res.render("WriteArticles", {
    title: "发表文章",
    post: {},
  });
});

router.post("/WriteArticles", check.checkLogin, async function (req, res) {
  // console.log(req.fields); // 文本键值对
  // console.log(req.files);
  // console.log(path.win32.basename(req.files.img.path));

  try {
    const { title, content } = req.body;

    const authorId = new ObjectId(req.session.user._id);
    const pv = 0,
      commentCount = 0;

    const img =
      req.files.img.size > 0
        ? `/upload/${path.win32.basename(req.files.img.path)}`
        : "";

    if (!title || !content) {
      throw new Error("标题和内容不能为空！");
    }

    const { insertedId } = await db.addOnePost({
      title,
      content,
      authorId,
      pv,
      commentCount,
      img,
    });

    req.flash("success", "文章发表成功！");
    return res.redirect(`/post/ArticleDetails/${insertedId}`);
  } catch (error) {
    req.flash("error", error.message);
    return res.redirect("back");
  }
});

// 获取单篇文章详情
// router.get('/ArticleDetails/:id', function (req, res, next) {
//   res.render('ArticleDetails', {
//     title: '文章详情',
//     post: {}
//   });
// });

router.get("/ArticleDetails/:id", async function (req, res, next) {
  let { id } = req.params;
  try {
    id = new ObjectId(id);
  } catch {
    return next(createError(404, "该篇文章不存在！"));
  }
  try {
    const post = await db.findOnePost({
      _id: id,
    });

    console.log("----", post);
    if (!post) {
      return next(createError(404, "该篇文章不存在！"));
    }

    post.content = marked.parse(post.content);

    return res.render("ArticleDetails", {
      title: post.title,
      post,
      comments: [],
    });
  } catch (error) {
    req.flash("error", error.message);
    return res.redirect("back");
  }
});

module.exports = router;
